<template>
  <div class="data-filter-container">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select
            v-model="searchForm.companyId"
            placeholder="请选择分公司"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-select
            v-model="searchForm.salesmanId"
            placeholder="请选择业务员"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="salesman in salesmanList"
              :key="salesman.id"
              :label="salesman.name"
              :value="salesman.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="客户类型">
          <el-select
            v-model="searchForm.customerType"
            placeholder="请选择客户类型"
            clearable
            style="width: 150px"
          >
            <el-option label="个人客户" value="personal" />
            <el-option label="企业客户" value="enterprise" />
            <el-option label="VIP客户" value="vip" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="业务类型">
          <el-select
            v-model="searchForm.businessType"
            placeholder="请选择业务类型"
            clearable
            style="width: 150px"
          >
            <el-option label="新房销售" value="new_house" />
            <el-option label="二手房" value="second_hand" />
            <el-option label="租赁" value="rental" />
            <el-option label="商业地产" value="commercial" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ formatNumber(statsData.totalAmount) }}</div>
            <div class="stats-label">总成交金额（万元）</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ statsData.totalCount }}</div>
            <div class="stats-label">总成交笔数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ formatNumber(statsData.avgAmount) }}</div>
            <div class="stats-label">平均成交金额（万元）</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ formatNumber(statsData.commission) }}</div>
            <div class="stats-label">总佣金（万元）</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>财务数据列表</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="salesmanName" label="业务员" width="100" />
        <el-table-column prop="companyName" label="分公司" width="120" />
        <el-table-column prop="businessType" label="业务类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getBusinessTypeTag(row.businessType)">
              {{ getBusinessTypeName(row.businessType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="成交金额（万元）" width="140" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="佣金（万元）" width="120" align="right">
          <template #default="{ row }">
            <span class="commission-text">{{ formatNumber(row.commission) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dealDate" label="成交日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const searchFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  companyId: '',
  salesmanId: '',
  customerType: '',
  businessType: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 表格数据
const tableData = ref([])
const selectedRows = ref([])

// 统计数据
const statsData = reactive({
  totalAmount: 0,
  totalCount: 0,
  avgAmount: 0,
  commission: 0
})

// 下拉选项
const companyList = ref([])
const salesmanList = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 方法
const handleSearch = () => {
  pagination.page = 1
  getTableData()
}

const handleReset = () => {
  searchFormRef.value?.resetFields()
  Object.assign(searchForm, {
    dateRange: [],
    companyId: '',
    salesmanId: '',
    customerType: '',
    businessType: ''
  })
  handleSearch()
}

const handleExport = () => {
  exportLoading.value = true
  // TODO: 实现导出功能
  setTimeout(() => {
    exportLoading.value = false
    ElMessage.success('导出成功')
  }, 2000)
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    // const response = await getFinanceDataList(searchForm, pagination)
    
    // 模拟数据
    setTimeout(() => {
      tableData.value = [
        {
          id: 1,
          customerName: '张三',
          salesmanName: '李四',
          companyName: '北京分公司',
          businessType: 'new_house',
          amount: 150.5,
          commission: 4.5,
          dealDate: '2025-08-15',
          status: 'completed'
        }
      ]
      pagination.total = 100
      
      // 更新统计数据
      Object.assign(statsData, {
        totalAmount: 1250.8,
        totalCount: 45,
        avgAmount: 27.8,
        commission: 37.5
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const handleAdd = () => {
  // TODO: 打开新增对话框
  ElMessage.info('新增功能开发中')
}

const handleEdit = (row: any) => {
  // TODO: 打开编辑对话框
  ElMessage.info(`编辑 ${row.customerName} 的数据`)
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除客户 ${row.customerName} 的财务数据吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用删除API
    ElMessage.success('删除成功')
    getTableData()
  })
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getBusinessTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    new_house: 'success',
    second_hand: 'primary',
    rental: 'warning',
    commercial: 'info'
  }
  return tagMap[type] || 'info'
}

const getBusinessTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    new_house: '新房销售',
    second_hand: '二手房',
    rental: '租赁',
    commercial: '商业地产'
  }
  return nameMap[type] || type
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    completed: 'success',
    pending: 'warning',
    cancelled: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    completed: '已完成',
    pending: '待处理',
    cancelled: '已取消'
  }
  return nameMap[status] || status
}

// 初始化数据
const initData = async () => {
  // TODO: 获取下拉选项数据
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' }
  ]
  
  salesmanList.value = [
    { id: '1', name: '李四' },
    { id: '2', name: '王五' },
    { id: '3', name: '赵六' }
  ]
  
  getTableData()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.data-filter-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-item {
        text-align: center;
        
        .stats-value {
          font-size: 28px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 8px;
        }
        
        .stats-label {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .commission-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
